package com.aaa.sys.controller;


import com.aaa.vo.R;
import com.aaa.sys.entity.Notice;
import com.aaa.sys.service.NoticeService;
import com.aaa.sys.vo.NoticeResult;
import com.aaa.sys.vo.NoticeVo;
import com.aaa.util.JwtUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 通知表 前端控制器
 * </p>
 *
 * @author ykq
 * @since 2020-12-08
 */
@RestController
@RequestMapping("/system/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @PostMapping("findByCondication/{page}/{limit}")
    public R findByCondication(@PathVariable Integer page,@PathVariable Integer limit, @RequestBody NoticeVo noticeVo){
        IPage<NoticeResult> page1= this.noticeService.findByCondication(page,limit,noticeVo);
        return R.ok().data("records",page1.getRecords()).data("total",page1.getTotal());
    }

    @GetMapping("findById/{noticeId}")
    public R findById(@PathVariable Long noticeId){
        Notice notice = this.noticeService.getById(noticeId);
        return R.ok().data("notice",notice);
    }

    @PostMapping("saveNotice")
    public R saveNotice(@RequestBody Notice notice, HttpServletRequest request){
        try {
            notice.setCreateTime(new Date());
            notice.setCreateUser(JwtUtils.getMemberIdByJwtToken(request.getHeader("token")));
            boolean save = this.noticeService.save(notice);
            return R.ok().message("添加通告成功");
        }catch (Exception e){
            return R.error().message("添加通告失败");
        }
    }
    @PostMapping("updateNotice")
    public R updateNotice(@RequestBody Notice notice, HttpServletRequest request){
        try {
            notice.setUpdateTime(new Date());
            notice.setUpdateUser(JwtUtils.getMemberIdByJwtToken(request.getHeader("token")));
            boolean save = this.noticeService.updateById(notice);
            return R.ok().message("修改通告成功");
        }catch (Exception e){
            return R.error().message("修改通告失败");
        }
    }

    @DeleteMapping("deleteNotice/{noticeId}")
    public R deleteNotice(@PathVariable Long noticeId){
        try {
            boolean b = this.noticeService.removeById(noticeId);
            return R.ok().message("删除通告成功");
        }catch (Exception e){
            return R.error().message("删除通告失败");
        }
    }
}

